package testcase;


import org.opengauss.jdbc.PgConnection;

import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 测试最小连接模式，在重启节点后，根据各节点连接数对集群连接负载平衡
 *
 */
public class CheckConnectionValidityTest {
  
  private final static String URL_DN3 = "jdbc:opengauss://192.168.0.243:14300/test";
  
  private final static String URL = "jdbc:opengauss://192.168.0.243:14100,192.168.0.243:14200,192.168.0.243:14300/test";
  
  private final static String LEASTCONN_PARAMS = "?autoBalance=leastconn";
  
  private final static String USERNAME = "test";
  
  private final static String PASSWORD = "huawei123.";
  
  // 不开启快速负载均衡功能，起始时创建30个连接，关闭一个节点，心跳线程会清理调已缓存的该节点上的连接。
  // 重启节点，新连接会优先在刚恢复的节点上建联。
  private static void testCreateConnectionAndCheckValidity() {
    Map<String, Integer> connectionMap = new ConcurrentHashMap<>();
    int num = 30;
    for (int i = 0; i < num; i++) {
      try {
        PgConnection pgConnection = (PgConnection) DriverManager.getConnection(URL + LEASTCONN_PARAMS + "&loggerLevel" +
                "=OFF", USERNAME,
            PASSWORD);
        String s = pgConnection.getSocketAddress().split("/")[1];
        connectionMap.put(s, connectionMap.getOrDefault(s, 0) + 1);
      } catch (SQLException e) {
        throw new RuntimeException(e);
      }
    }
    System.out.println(connectionMap.toString());

    // 每2秒新建一条连接。
    while (true) {
      try {
        // 手动关闭一个节点， 心跳线程会定时清理掉该节点下缓存的连接
        Thread.sleep(1000 * 2);
        // 重启节点
        PgConnection pgConnection = (PgConnection) DriverManager.getConnection(URL + LEASTCONN_PARAMS + "&loggerLevel" +
                "=OFF", USERNAME,
            PASSWORD);
        System.out.println("new connection: " + pgConnection.getSocketAddress().split("/")[1]);
      } catch (InterruptedException | SQLException e) {
        throw new RuntimeException(e);
      }
    }
  }
  
  public static void main(String[] args) {
    testCreateConnectionAndCheckValidity();
  }
}
